package com.debao.system.service.impl;

import java.util.*;

import com.alibaba.fastjson2.JSONObject;
import com.debao.common.constant.WechatConstants;
import com.debao.common.enums.OrderStatusEnum;
import com.debao.common.enums.StadiumTableOrderEnums;
import com.debao.common.model.TempData;
import com.debao.common.model.WechatTemplateVo;
import com.debao.common.utils.AliyunSmsUtil;
import com.debao.common.utils.StringUtils;
import com.debao.common.wechat.WechatUtils;
import com.debao.system.domain.Stadium;
import com.debao.system.domain.StadiumTable;
import com.debao.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.debao.system.mapper.StadiumTableOrderMapper;
import com.debao.system.domain.StadiumTableOrder;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * 预订场馆的订单Service业务层处理
 * 
 * @author DeBao
 * @date 2024-07-08
 */
@Service
@Slf4j
public class StadiumTableOrderServiceImpl implements IStadiumTableOrderService 
{
    @Autowired
    private StadiumTableOrderMapper stadiumTableOrderMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IConfigService configService;

    @Autowired
    private IStadiumService stadiumService;
    @Autowired
    private IStadiumTableService stadiumTableService;

    @Autowired
    private IStadiumTableScheduleService tableScheduleService;


    /**
     * 商品下单订阅通知模板Id
     */
    private static final String templateId = "4fwfJkMdj-nCgcabgByac3BuSb6NfiRuM6fepE5-XQU";

    /**
     * 查询预订场馆的订单
     * 
     * @param id 预订场馆的订单主键
     * @return 预订场馆的订单
     */
    @Override
    public StadiumTableOrder selectStadiumTableOrderById(Long id)
    {
        return stadiumTableOrderMapper.selectStadiumTableOrderById(id);
    }

    @Override
    public StadiumTableOrder selectStadiumTableOrderByOrderNo(String orderNo)
    {
        return stadiumTableOrderMapper.selectStadiumTableOrderByOrderNo(orderNo);
    }

    /**
     * 订单是否支付成功
     * @param orderNo
     * @return
     */
    @Override
    public Boolean isPaySuccess(String orderNo) {
        return stadiumTableOrderMapper.isPaySuccess(orderNo);
    }

    /**
     * 查询预订场馆的订单列表
     * 
     * @param stadiumTableOrder 预订场馆的订单
     * @return 预订场馆的订单
     */
    @Override
    public List<StadiumTableOrder> selectStadiumTableOrderList(StadiumTableOrder stadiumTableOrder)
    {
        return stadiumTableOrderMapper.selectStadiumTableOrderList(stadiumTableOrder);
    }

    /**
     * 新增预订场馆的订单
     * 
     * @param stadiumTableOrder 预订场馆的订单
     * @return 结果
     */
    @Override
    public int insertStadiumTableOrder(StadiumTableOrder stadiumTableOrder)
    {
        return stadiumTableOrderMapper.insertStadiumTableOrder(stadiumTableOrder);
    }


    /**
     * 处理支付成功回调
     *
     * @param orderNo
     * @param transactionId
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
    public void paySucHandleOrder(String orderNo, String transactionId) {
        if (StringUtils.isBlank(orderNo)){
            log.error("订单数据更新失败，orderNo为空");
            return;
        }
        String logHead = String.format("订单回调更新, orderNo = %s ", orderNo);
        //获取订单信息
        StadiumTableOrder stadiumTableOrder = stadiumTableOrderMapper.selectStadiumTableOrderByOrderNo(orderNo);


        if (Objects.isNull(stadiumTableOrder)){
            // todo 自定义异常类
            log.error(logHead + "订单不存在");
            return;
        }
        if (!StringUtils.equalsIgnoreCase(stadiumTableOrder.getStatus(),String.valueOf(OrderStatusEnum.None))){
            log.error(logHead + "订单信息回调已更新 status = {}", stadiumTableOrder.getStatus());
            return;
        }
        //更新订单状态
        stadiumTableOrder.setTransactionId(transactionId);
        stadiumTableOrder.setPayAt(new Date());
        stadiumTableOrder.setPayMoney(stadiumTableOrder.getMoney());
        stadiumTableOrder.setStatus(String.valueOf(StadiumTableOrderEnums.Paid));
        int row = stadiumTableOrderMapper.updateStadiumTableOrder(stadiumTableOrder);
        if (row !=1){
            log.error(logHead + "订单更新失败");
        }
        //更新桌台状态
        // todo 更新桌台状态(根据订单号更新状态为 0 )
        int result = tableScheduleService.updateStatus(orderNo);
        if (result !=1){
            log.error(logHead + "桌台状态失败");
        }
//        消息推送
        if (row == 1) {
            Stadium stadium = stadiumService.selectStadiumById(stadiumTableOrder.getStadiumId());
            StadiumTable stadiumTable = stadiumTableService.selectStadiumTableById(stadiumTableOrder.getStadiumTableId());
            //异步方式实现短信推送 通知给用户
            Thread threadMsg = new Thread(() -> {
                synchronized (this) {
                    //获取用户手机号码
                    try {
                        String phone = userService.getPhoneByUserId(stadiumTableOrder.getUserId());
                        if (!phone.isEmpty()) {
                            HashMap<String, String> map = new HashMap<>();
                            map.put("venue", stadium.getName()); //场馆
                            map.put("price", stadiumTable.getPrice() / 100 + "元/小时");
                            map.put("money", stadiumTableOrder.getPayMoney() / 100 + "元/小时");
                            map.put("desk", stadiumTable.getName());
                            map.put("date",stadiumTableOrder.getDate());
                            map.put("time", stadiumTableOrder.getTime());
                            AliyunSmsUtil.sendSms(phone, "SMS_474510015", JSONObject.toJSONString(map));
                        }
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    //订阅消息通知 通知给下单的用户
                    String token = configService.selectValueByKey(WechatConstants.APP_TOKEN);
                    //获取用户openid
                    String openId = userService.getOpenIdByUserId(stadiumTableOrder.getUserId());
                    if (openId.isEmpty()) {
                        return;
                    }
                    Map<String, TempData> data = new HashMap<>();
                    data.put("thing8", new TempData(stadium.getName()));
                    data.put("thing3", new TempData(stadiumTable.getName()));
                    data.put("time1", new TempData(stadiumTableOrder.getDate()));
                    data.put("time2", new TempData(stadiumTableOrder.getTime()));
                    data.put("amount4", new TempData((stadiumTableOrder.getPayMoney() / 100)+"元"));
                    WechatUtils.postTemplateData(new WechatTemplateVo().setTemplateId(templateId).setToken(token).setOpenid(openId).setData(data).setPage("/subPackages/order/details/stadum_detail?orderNo=" + orderNo));
                }
            });
            threadMsg.start();
        }
    }

    /**
     * 修改预订场馆的订单
     * 
     * @param stadiumTableOrder 预订场馆的订单
     * @return 结果
     */
    @Override
    public int updateStadiumTableOrder(StadiumTableOrder stadiumTableOrder)
    {
        return stadiumTableOrderMapper.updateStadiumTableOrder(stadiumTableOrder);
    }

    /**
     * 批量删除预订场馆的订单
     * 
     * @param ids 需要删除的预订场馆的订单主键
     * @return 结果
     */
    @Override
    public int deleteStadiumTableOrderByIds(Long[] ids)
    {
        return stadiumTableOrderMapper.deleteStadiumTableOrderByIds(ids);
    }

    /**
     * 删除预订场馆的订单信息
     * 
     * @param id 预订场馆的订单主键
     * @return 结果
     */
    @Override
    public int deleteStadiumTableOrderById(Long id)
    {
        return stadiumTableOrderMapper.deleteStadiumTableOrderById(id);
    }


}
